from datetime import datetime

from src.application.user import dto
from src.application.user.use_cases.get_users import GetUsers, GetUsersHandler
from src.domain.common.constants import Empty, OrderBy
from tests.mocks.uow import UnitOfWorkMock


async def test_get_users_handler_success(uow: UnitOfWorkMock) -> None:
    users: list[dto.UserDTOs] = [
        dto.UserDTO(id=0, tg_id=123, username="test", was_registered=datetime.now()),
        dto.UserDTO(id=1, tg_id=321, username="test1", was_registered=datetime.now()),
    ]
    await uow.user_reader.add_users(users)
    handler = GetUsersHandler(uow=uow)

    query = GetUsers(
        is_registered=Empty.UNSET,
        offset=0,
        limit=10,
        order=OrderBy.DESC,
    )
    result = await handler(query)

    assert result.users == sorted(users, key=lambda user: user.tg_id, reverse=True)
    assert result.total == len(users)
    assert result.offset == query.offset
    assert result.limit == query.limit


async def test_get_users_handler_no_users(uow: UnitOfWorkMock) -> None:
    handler = GetUsersHandler(uow=uow)
    users: list[dto.UserDTOs] = [
        dto.UserDTO(id=0, tg_id=123, username="test", was_registered=datetime.now()),
        dto.UserDTO(id=1, tg_id=321, username="test1", is_registered=True, was_registered=datetime.now()),
    ]
    await uow.user_reader.add_users(users)

    query = GetUsers(
        is_registered=True,
        offset=0,
        limit=10,
        order=OrderBy.ASC,
    )
    result = await handler(query)

    assert result.users == [users[1]]
    assert result.total == 1
    assert result.offset == query.offset
    assert result.limit == query.limit
